package com.lhs.time;



import com.lhs.entity.search.HotSearchHistory;
import lombok.RequiredArgsConstructor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.List;
import java.util.Set;

@Component
@RequiredArgsConstructor
public class HotSearchPersistTask {

    private final StringRedisTemplate redisTemplate;
    private final MongoTemplate mongoTemplate;
    private static final String HOT_KEY = "search:hot";

    /**
     * 定时持久化热搜数据到MongoDB
     * 每天凌晨2点执行，将Redis中存储的热搜排行榜数据取出并保存到MongoDB中
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void persistHotSearch() {
        // 从Redis中获取热搜排行榜前100条数据及其分数
        Set<ZSetOperations.TypedTuple<String>> top = redisTemplate.opsForZSet().reverseRangeWithScores(HOT_KEY, 0, 99);
        if (top == null) return;

        // 将Redis中的数据转换为HotSearchHistory对象列表
        List<HotSearchHistory> list = top.stream()
                .map(t -> new HotSearchHistory(LocalDate.now(), t.getValue(), t.getScore()))
                .toList();

        // 批量插入到MongoDB中
        mongoTemplate.insertAll(list);
    }

}
